package com.mzx.thread;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;

//创建线程的第一种方法
//练习Thread，实现多线程同步下载图片
//1.实现一个线程类，首先继承threa类
public class DownloadPicture extends Thread{
    private String url;//网络图片的地址
    private String name;//保存文件的名字

    //用构造器来实现变量的初始值
   public DownloadPicture(String url,String name){
       this.url=url;
       this.name=name;
   }
   
    //2.重写run方法，也就是下载图片线程的执行体
    @Override
    public void run() {
        WebDownloader webDownloader = new WebDownloader();
        webDownloader.downloader(url,name);
        System.out.println("下载了文件名为："+name);
    }

    public static void main(String[] args) {
        DownloadPicture t1 = new DownloadPicture("https://www.veer.com/photo/300957041","1.jpg");
        DownloadPicture t2 = new DownloadPicture("https://www.veer.com/photo/131936618","2.jpg");
        DownloadPicture t3 = new DownloadPicture("https://www.veer.com/photo/132868867","3.jpg");

        //启动线程
        t1.start();
        t2.start();
        t3.start();
    }
}

//一个下载器
class WebDownloader{
    //下载方法，用到两个参数，url和name
    public void downloader(String url,String name){
        try {
            //通过FileUtils的工具类的copyURLToFile的方法，就是把一个url变成文件
            FileUtils.copyURLToFile(new URL(url),new  File(name));
            //就是返回一个把图片下载下来
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("IO异常，downloader方法出现问题");
        }

    }
}